"use client";
import { AntdRegistry } from "@ant-design/nextjs-registry";
import "./globals.css";
import BasicLayout from "@/layouts/BasicLayout";
import React, { useCallback, useEffect } from "react";
import { Provider, useDispatch, useSelector } from "react-redux";
import store, { AppDispatch, RootState } from "@/stores";
import { Axios } from "axios";
import { getCurrentUserUsingGet } from "@/api/userController";
import { setLoginUser } from "@/stores/loginUser";
import { usePathname } from "next/navigation";
import AccessLayout from "@/access/AccessLayout";
import ACCESS_ENUM from "@/access/accessEnum";
import {DEFAULT_USER} from "@/constant/user";
import MessageLayout from "@/app/my/message/layout";
import { queryFriendMessageRequestUsingPost } from "@/api/userRelationshipController";

/**
 * 全局布局文件
 * 全局初始化逻辑
 * @param children
 * @constructor
 */
const InitLayout: React.FC<
    Readonly<{
      children: React.ReactNode;
    }>
> = ({ children }) => {
  const dispatch = useDispatch<AppDispatch>();
  const loginUser = useSelector((state: RootState) => state.loginUser);

  // 消息统计函数
  const loadMessageCounts = useCallback(async () => {
    try {
      // 获取好友请求数量
      const { data: friendRequests } = await queryFriendMessageRequestUsingPost();
      const followCount = Array.isArray(friendRequests) ? friendRequests.length : 0;
      
      // TODO: 后续实现其他消息数量的获取
      const commentCount = Array.isArray(friendRequests) ? friendRequests.length : 0; // 评论数量
      const thumbCount = Array.isArray(friendRequests) ? friendRequests.length : 0;   // 点赞数量
      const systemCount = Array.isArray(friendRequests) ? friendRequests.length : 0;  // 系统消息数量
      
      // 计算总数
      const totalCount = commentCount + thumbCount + followCount + systemCount;
      
      window.dispatchEvent(new CustomEvent('updateNotificationCount', {
        detail: { 
          count: totalCount
        }
      }));
    } catch (error) {
      console.error('Failed to load message counts:', error);
    }
  }, []);

  // useCallback函数起缓存作用，减少重复请求
  const doInitLoginUser = useCallback(async () => {
    const res = await getCurrentUserUsingGet();
    if (res.data) {
      // 保存用户登录态
      dispatch(setLoginUser(res.data as API.FunRiceUser));
      
      // 初始化消息统计
      try {
        const { data: friendRequests } = await queryFriendMessageRequestUsingPost();
        const followCount = Array.isArray(friendRequests) ? friendRequests.length : 0;
        const commentCount = Array.isArray(friendRequests) ? friendRequests.length : 0;
        const thumbCount = Array.isArray(friendRequests) ? friendRequests.length : 0;
        const systemCount = Array.isArray(friendRequests) ? friendRequests.length : 0;
        
        // 计算总数
        const totalCount = commentCount + thumbCount + followCount + systemCount;
        
        window.dispatchEvent(new CustomEvent('updateNotificationCount', {
          detail: { 
            count: totalCount
          }
        }));
      } catch (error) {
        console.error('Failed to load message counts:', error);
      }
    } else {
      dispatch(setLoginUser(DEFAULT_USER));
      if (
          !window.location.pathname.includes("/user/register")&&
          !window.location.pathname.includes("/user/login")
      ) {
        window.location.href = `/user/login?redirect=${window.location.href}`;
      }
    }
  }, [dispatch]);

  // 初始化用户信息
  useEffect(() => {
    doInitLoginUser();
  }, [doInitLoginUser]);

  // 设置消息统计定时器
  useEffect(() => {
    if (loginUser?.id) {
      // 设置定时器，每30秒执行一次
      const timer = setInterval(loadMessageCounts, 30000);
      
      // 监听消息更新事件
      const handleMessageUpdate = () => {
        loadMessageCounts();
      };
      
      window.addEventListener('updateMessage', handleMessageUpdate);
      
      // 组件卸载时清理定时器和事件监听
      return () => {
        clearInterval(timer);
        window.removeEventListener('updateMessage', handleMessageUpdate);
      };
    }
  }, [loginUser?.id, loadMessageCounts]);

  return children;
};
export default function RootLayout({
                                     children,
                                   }: Readonly<{
  children: React.ReactNode;
}>) {
  return (
      <html lang="zh">
      <body>
      <AntdRegistry>
        <Provider store={store}>
          <InitLayout>
            <BasicLayout>
              <AccessLayout>{children}</AccessLayout>
            </BasicLayout>
          </InitLayout>
        </Provider>
      </AntdRegistry>
      </body>
      </html>
  );
}
